<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <p>{{ error }}</p>
    <!-- <p>{{ form.rules[prop] }}</p> -->
  </div>
</template>

<script>
import Validator from "async-validator";
export default {
  inject: ["form"],
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: String,
  },
  data() {
    return {
      error: "",
    };
  },
  mounted() {
    // console.log(this.form);
    this.$on("validate", () => {
      this.validate();
    });
  },
  methods: {
    validate() {
      // console.log('console');
      // 加载一个校验库，async-validator
      // 1. 获取校验规则和值
      const rules = this.form.rules[this.prop];
      const value = this.form.model[this.prop];
      // 2. 创建一个校验器实例
      const validator = new Validator({ [this.prop]: rules });
      validator.validate({ [this.prop]: value }, (errors) => {
        if (errors) {
          this.error = errors[0].message;
        } else {
          this.error = "";
        }
      });
    },
  },
};
</script>

<style>
</style>